{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a91acd66",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'C:\\\\Users\\\\oscar'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "os.getcwd()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2629c086",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.chdir('C:\\\\Users\\\\oscar\\\\Documents\\\\experimentos\\\\2025_Four_carnivores_MAML')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3b5b3996",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the directory where you want to save the best model\n",
    "save_dir = 'C:\\\\Users\\\\oscar\\\\Documents\\\\experimentos\\\\2025_Four_carnivores_MAML\\\\bestmodels\\\\FinalModels2025'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ebbc501b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.preprocessing import image\n",
    "import keras.backend as K\n",
    "import numpy as np\n",
    "import cv2\n",
    "import sys\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d6a3dcbd",
   "metadata": {},
   "outputs": [],
   "source": [
    "model1_path = os.path.join(save_dir, 'last_epoch_resnet50.h5')\n",
    "model1 = tf.keras.models.load_model(model1_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "7998783d",
   "metadata": {},
   "outputs": [],
   "source": [
    "model2_path = os.path.join(save_dir, 'last_epoch_resnet152.h5')\n",
    "model2 = tf.keras.models.load_model(model2_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "876bf0ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "model3_path = os.path.join(save_dir, 'last_epoch_exception.h5')\n",
    "model3 = tf.keras.models.load_model(model3_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ba25d711",
   "metadata": {},
   "outputs": [],
   "source": [
    "model4_path = os.path.join(save_dir, 'last_epoch_efficient.h5')\n",
    "model4 = tf.keras.models.load_model(model4_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c80b2774",
   "metadata": {},
   "outputs": [],
   "source": [
    "model5_path = os.path.join(save_dir, 'last_epoch_densenet.h5')\n",
    "model5 = tf.keras.models.load_model(model5_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "e56ac6c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "members=[model1,model2,model3,model4,model5]#actualizar!!!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b532a313",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0fc42f9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "64d3cab5",
   "metadata": {},
   "outputs": [],
   "source": [
    "#loads image to be classified. Activate libraries\n",
    "\n",
    "from tensorflow.keras.preprocessing import image\n",
    "import keras.backend as K\n",
    "import numpy as np\n",
    "import cv2\n",
    "import sys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8056f4c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "#con esto cargas todas las imágenes y las clasificas usando Resnet50:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9c6c8672",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from tensorflow.keras.preprocessing import image\n",
    "from keras.applications.resnet50 import preprocess_input as preprocess_resnet50\n",
    "\n",
    "# Path to the folder containing images\n",
    "folder_path = 'C:\\\\Users\\\\oscar\\\\Documents\\\\experimentos\\\\2025_Four_carnivores_MAML\\\\oh7bis'  # Directory with images\n",
    "\n",
    "# List all files in the folder\n",
    "image_files = os.listdir(folder_path)\n",
    "\n",
    "# Define class labels (modify according to your model)\n",
    "class_labels = {0: \"crocodile\", 1: \"hyena\", 2: \"leopard\", 3: \"lion\"}  # Example class names\n",
    "\n",
    "# Create lists to store results\n",
    "file_names = []\n",
    "predicted_labels = []\n",
    "probabilities = []\n",
    "\n",
    "# Iterate over each image file\n",
    "for file_name in image_files:\n",
    "    # Load and preprocess the image\n",
    "    img_path = os.path.join(folder_path, file_name)\n",
    "    img = image.load_img(img_path, target_size=(224, 224))\n",
    "    \n",
    "    img_resnet50 = image.img_to_array(img)\n",
    "    img_resnet50 = np.expand_dims(img_resnet50, axis=0)\n",
    "    img_resnet50 = preprocess_resnet50(img_resnet50)\n",
    "\n",
    "    # Make prediction\n",
    "    prediction_resnet50 = members[1].predict(img_resnet50)  # Using model2 (ResNet152)\n",
    "    \n",
    "    # Get the predicted class index\n",
    "    predicted_class_index = np.argmax(prediction_resnet50, axis=1)[0]\n",
    "\n",
    "    # Get the class label using the dictionary\n",
    "    predicted_label = class_labels.get(predicted_class_index, \"Unknown\")\n",
    "\n",
    "    # Round probabilities to 3 decimal places\n",
    "    rounded_probs = np.round(prediction_resnet50.flatten(), 3)\n",
    "\n",
    "    # Append results\n",
    "    file_names.append(file_name)\n",
    "    predicted_labels.append(predicted_label)\n",
    "    probabilities.append(rounded_probs.tolist())  # Convert array to list\n",
    "\n",
    "# Create a DataFrame with properly rounded probabilities\n",
    "results_df = pd.DataFrame({\n",
    "    'File Name': file_names,\n",
    "    'Predicted Label': predicted_labels,\n",
    "    'Probabilities': [list(map(lambda x: round(x, 3), prob)) for prob in probabilities]  # Round each probability to 3 decimals\n",
    "})\n",
    "\n",
    "# Print the DataFrame\n",
    "print(results_df)\n",
    "\n",
    "# Export the DataFrame to a CSV file in the folder_path\n",
    "#results_df.to_csv(os.path.join(folder_path, 'predictionsResnet.csv'), index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9d77561e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6c903eb",
   "metadata": {},
   "outputs": [],
   "source": [
    "#ESTO ES POR SI QUIERES HACER ENSEMBLE ANALISIS CON LOS TRES MODELOS JUNTOS Y CON LAS IMÁGENES PRE-PROCESADAS CON LOS TRES MODELOS. ES UN PROCESO PONDERADO. LLAMAME Y TYE EXPLICO QUE ES. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd4392c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from keras.preprocessing import image\n",
    "from keras.applications.resnet50 import preprocess_input as preprocess_resnet50\n",
    "from keras.applications.resnet import preprocess_input as preprocess_resnet152\n",
    "from keras.applications.xception import preprocess_input as preprocess_xception\n",
    "from keras.applications.efficientnet import preprocess_input as preprocess_efficientnet\n",
    "from keras.applications.densenet import preprocess_input as preprocess_densenet\n",
    "import numpy as np\n",
    "\n",
    "# Define the accuracies of the models\n",
    "accuracies = [82, 83.59, 81.54, 81, 82.56]  # Accuracy of each model (update with your actual model accuracies)\n",
    "\n",
    "# Find the maximum accuracy\n",
    "max_accuracy = max(accuracies)\n",
    "\n",
    "# Calculate the weights\n",
    "weights = [(accuracy / max_accuracy) for accuracy in accuracies]\n",
    "\n",
    "# Path to the folder containing images\n",
    "folder_path = 'C:\\\\Users\\\\oscar\\\\Documents\\\\experimentos\\\\2025_Four_carnivores_MAML\\\\oh7bis'  # Directory where the images are stored\n",
    "\n",
    "# List all files in the folder\n",
    "image_files = os.listdir(folder_path)\n",
    "\n",
    "# Define class labels (modify according to your model)\n",
    "class_labels = {0: \"crocodile\", 1: \"hyena\", 2: \"leopard\", 3: \"lion\"}  # Example class names\n",
    "\n",
    "# Iterate over each image file\n",
    "for file_name in image_files:\n",
    "    # Load the image\n",
    "    img_path = os.path.join(folder_path, file_name)\n",
    "    img = image.load_img(img_path, target_size=(299, 299))  # Use 299x299 for Xception and EfficientNet V2L\n",
    "\n",
    "    # Preprocess the image for each model based on size\n",
    "    img_resnet50 = image.load_img(img_path, target_size=(224, 224))  # 224x224 for ResNet50 and DenseNet\n",
    "    img_resnet50 = image.img_to_array(img_resnet50)\n",
    "    img_resnet50 = np.expand_dims(img_resnet50, axis=0)\n",
    "    img_resnet50 = preprocess_resnet50(img_resnet50)\n",
    "\n",
    "    img_resnet152 = image.load_img(img_path, target_size=(224, 224))  # 224x224 for ResNet152\n",
    "    img_resnet152 = image.img_to_array(img_resnet152)\n",
    "    img_resnet152 = np.expand_dims(img_resnet152, axis=0)\n",
    "    img_resnet152 = preprocess_resnet152(img_resnet152)\n",
    "\n",
    "    img_xception = image.load_img(img_path, target_size=(299, 299))  # 299x299 for Xception\n",
    "    img_xception = image.img_to_array(img_xception)\n",
    "    img_xception = np.expand_dims(img_xception, axis=0)\n",
    "    img_xception = preprocess_xception(img_xception)\n",
    "\n",
    "    img_efficientnet = image.load_img(img_path, target_size=(299, 299))  # 299x299 for EfficientNet V2L\n",
    "    img_efficientnet = image.img_to_array(img_efficientnet)\n",
    "    img_efficientnet = np.expand_dims(img_efficientnet, axis=0)\n",
    "    img_efficientnet = preprocess_efficientnet(img_efficientnet)\n",
    "\n",
    "    img_densenet = image.load_img(img_path, target_size=(224, 224))  # 224x224 for DenseNet\n",
    "    img_densenet = image.img_to_array(img_densenet)\n",
    "    img_densenet = np.expand_dims(img_densenet, axis=0)\n",
    "    img_densenet = preprocess_densenet(img_densenet)\n",
    "\n",
    "    # Now, make predictions with each model in the ensemble\n",
    "    prediction_resnet50 = members[0].predict(img_resnet50)\n",
    "    prediction_resnet152 = members[1].predict(img_resnet152)\n",
    "    prediction_xception = members[2].predict(img_xception)\n",
    "    prediction_efficientnet = members[3].predict(img_efficientnet)\n",
    "    prediction_densenet = members[4].predict(img_densenet)\n",
    "\n",
    "    # Combine predictions according to the ensemble strategy (average predictions)\n",
    "    final_prediction = (prediction_resnet50 + prediction_resnet152 + prediction_xception + prediction_efficientnet + prediction_densenet) / 5\n",
    "    \n",
    "    # Weighted prediction based on model accuracies\n",
    "    weighted_prediction = (prediction_resnet50 * weights[0] + prediction_resnet152 * weights[1] + \n",
    "                           prediction_xception * weights[2] + prediction_efficientnet * weights[3] + \n",
    "                           prediction_densenet * weights[4])\n",
    "    \n",
    "    # Normalize the weighted prediction\n",
    "    total_sum = weighted_prediction.sum()\n",
    "    normalized_prediction = weighted_prediction / total_sum\n",
    "\n",
    "    # Get predicted class index\n",
    "    predicted_class_index = np.argmax(normalized_prediction, axis=1)[0]\n",
    "\n",
    "    # Get the predicted label using the class_labels dictionary\n",
    "    predicted_label = class_labels.get(predicted_class_index, \"Unknown\")\n",
    "\n",
    "    # Round probabilities to 3 decimal places\n",
    "    rounded_probabilities = np.round(normalized_prediction[0], 3)\n",
    "\n",
    "    # Extract label from the image file name\n",
    "    label = file_name.split('.')[0]  # Assuming the label is the part of the file name before the first period\n",
    "    \n",
    "    # Print the final prediction, the corresponding label, and probabilities\n",
    "    print(f'File Name: {file_name}')\n",
    "    print(f'Predicted Label: {predicted_label}')\n",
    "    print(f'Predicted Probabilities: {rounded_probabilities}')\n",
    "    print(f'Label from Filename: {label}\\n')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26ba60b1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afdfb486",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Export the DataFrame to a CSV file in the folder_path#results_df.to_csv(os.path.join(folder_path, 'predictionsResnet.csv'), index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0183e2dc",
   "metadata": {},
   "outputs": [],
   "source": [
    "#usar para guardar resultados en Excel\n",
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from keras.preprocessing import image\n",
    "from keras.applications.resnet50 import preprocess_input as preprocess_resnet50\n",
    "from keras.applications.resnet import preprocess_input as preprocess_resnet152\n",
    "from keras.applications.xception import preprocess_input as preprocess_xception\n",
    "from keras.applications.efficientnet import preprocess_input as preprocess_efficientnet\n",
    "from keras.applications.densenet import preprocess_input as preprocess_densenet\n",
    "\n",
    "# Define the accuracies of the models\n",
    "accuracies = [82, 83.59, 81.54, 81, 82.56]  # Accuracy of each model (update with actual values)\n",
    "\n",
    "# Find the maximum accuracy\n",
    "max_accuracy = max(accuracies)\n",
    "\n",
    "# Calculate the weights\n",
    "weights = [(accuracy / max_accuracy) for accuracy in accuracies]\n",
    "\n",
    "# Path to the folder containing images\n",
    "folder_path = 'C:\\\\Users\\\\oscar\\\\Documents\\\\experimentos\\\\2025_Four_carnivores_MAML\\\\oh7'  \n",
    "\n",
    "# List all files in the folder\n",
    "image_files = os.listdir(folder_path)\n",
    "\n",
    "# Define class labels (modify according to your model)\n",
    "class_labels = {0: \"crocodile\", 1: \"hyena\", 2: \"leopard\", 3: \"lion\"}  \n",
    "\n",
    "# Initialize an empty list to store results\n",
    "results = []\n",
    "\n",
    "# Iterate over each image file\n",
    "for file_name in image_files:\n",
    "    img_path = os.path.join(folder_path, file_name)\n",
    "\n",
    "    # Preprocess the image for each model based on required sizes\n",
    "    img_resnet50 = image.load_img(img_path, target_size=(224, 224))\n",
    "    img_resnet50 = np.expand_dims(image.img_to_array(img_resnet50), axis=0)\n",
    "    img_resnet50 = preprocess_resnet50(img_resnet50)\n",
    "\n",
    "    img_resnet152 = image.load_img(img_path, target_size=(224, 224))\n",
    "    img_resnet152 = np.expand_dims(image.img_to_array(img_resnet152), axis=0)\n",
    "    img_resnet152 = preprocess_resnet152(img_resnet152)\n",
    "\n",
    "    img_xception = image.load_img(img_path, target_size=(299, 299))\n",
    "    img_xception = np.expand_dims(image.img_to_array(img_xception), axis=0)\n",
    "    img_xception = preprocess_xception(img_xception)\n",
    "\n",
    "    img_efficientnet = image.load_img(img_path, target_size=(299, 299))\n",
    "    img_efficientnet = np.expand_dims(image.img_to_array(img_efficientnet), axis=0)\n",
    "    img_efficientnet = preprocess_efficientnet(img_efficientnet)\n",
    "\n",
    "    img_densenet = image.load_img(img_path, target_size=(224, 224))\n",
    "    img_densenet = np.expand_dims(image.img_to_array(img_densenet), axis=0)\n",
    "    img_densenet = preprocess_densenet(img_densenet)\n",
    "\n",
    "    # Make predictions\n",
    "    prediction_resnet50 = members[0].predict(img_resnet50)\n",
    "    prediction_resnet152 = members[1].predict(img_resnet152)\n",
    "    prediction_xception = members[2].predict(img_xception)\n",
    "    prediction_efficientnet = members[3].predict(img_efficientnet)\n",
    "    prediction_densenet = members[4].predict(img_densenet)\n",
    "\n",
    "    # Weighted prediction\n",
    "    weighted_prediction = (prediction_resnet50 * weights[0] + prediction_resnet152 * weights[1] + \n",
    "                           prediction_xception * weights[2] + prediction_efficientnet * weights[3] + \n",
    "                           prediction_densenet * weights[4])\n",
    "    \n",
    "    # Normalize the weighted prediction\n",
    "    total_sum = weighted_prediction.sum()\n",
    "    normalized_prediction = weighted_prediction / total_sum\n",
    "\n",
    "    # Get predicted class index\n",
    "    predicted_class_index = np.argmax(normalized_prediction, axis=1)[0]\n",
    "\n",
    "    # Get the predicted label\n",
    "    predicted_label = class_labels.get(predicted_class_index, \"Unknown\")\n",
    "\n",
    "    # Round probabilities to 3 decimal places\n",
    "    rounded_probabilities = np.round(normalized_prediction[0], 3).tolist()  \n",
    "\n",
    "    # Extract label from filename\n",
    "    label = file_name.split('.')[0]  # Assuming the label is the part of the file name before the first period\n",
    "\n",
    "    # Append results to the list\n",
    "    results.append([file_name, predicted_label, rounded_probabilities, label])\n",
    "\n",
    "# Convert results to a pandas DataFrame\n",
    "df_results = pd.DataFrame(results, columns=['File Name', 'Predicted Label', 'Probabilities', 'Label from Filename'])\n",
    "\n",
    "# Save to an Excel file\n",
    "output_path = \"C:\\\\Users\\\\oscar\\\\Documents\\\\experimentos\\\\2025_Four_carnivores_MAML\\\\predictions.xlsx\"\n",
    "df_results.to_excel(output_path, index=False)\n",
    "\n",
    "print(f\"Results saved to {output_path}\")\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
